import log from "electron-log";
import { getIP } from "./apis/remoteIp";
import CommentHelper from "./commentHelper";


class CrawlerHelper {
    private _worksUrl: string;
    private _commentData: string[];
    private _userData: any[];
    private _mainWindow: any;
    constructor(worksUrl: string, commentData: string[], userData: any[], mainWindow: any) {
        this._worksUrl = worksUrl;
        this._commentData = commentData;
        this._userData = userData;
        this._mainWindow = mainWindow;
    }

    async start(isProxy: boolean) {
      for (let i = 0;i < this._commentData.length; i++) {
        await this.commentTask(this._commentData[i], this._userData[i], isProxy);
      }  
    };

    async commentTask(commentStr: string, user: any, isProxy: boolean) {
        const commenthelper = new CommentHelper();
        let ip = '';
        if (isProxy) {
            ip = await this.getIP();
        }
        await commenthelper.init(user, ip);
        const suc = await retriesComment(commenthelper, this._worksUrl, commentStr, 3);
        if (suc) {
            this._mainWindow?.webContents.send('comment-step', `${user.userId}评论${commentStr}成功`);
        } else {
            this._mainWindow?.webContents.send('comment-step', `${user.userId}评论${commentStr}失败`);
        }
    }

    async getIP(): Promise<string> {
        try {
          const ipRes = await getIP(1);
          if (ipRes.data.code === 200) {
            const ipObj = ipRes.data.data[0];
            // ipObj.ip  ipObj.port
            return `${ipObj.ip}:${ipObj.port}`;
          }
        } catch (error) {
            log.info(JSON.stringify(error));
        }

        return '';
    }
}

const retriesComment = async (commenthelper: CommentHelper, worksUrl: string, commentStr: string, times: number): Promise<boolean> => {
    const suc = await commenthelper.commentWorks(worksUrl, commentStr);
    if (suc) {
        return true;
    } else {
        if (times > 0) {
            return retriesComment(commenthelper, worksUrl, commentStr, times - 1);
        }
    }

    return false;
}

export default CrawlerHelper;
